package com.example.cloud.controller.finance;

import com.alibaba.fastjson.JSONObject;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.controller.common.BaseController;
import com.example.cloud.dao.finance.AccountChangeDetailsRepository;
import com.example.cloud.dao.finance.GiftRecordRepository;
import com.example.cloud.model.dto.QueryModel;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.AccountChangeDetails;
import com.example.cloud.model.finance.GiftRecord;
import com.example.cloud.utils.ResultUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wangtao on 2018/7/31.
 */
@RestController
@RequestMapping("/gift/record")
public class GiftRecordController extends BaseController {

    @Autowired
    private GiftRecordRepository giftRecordRepository;

    @Autowired
    private AccountChangeDetailsRepository accountChangeDetailsRepository;

    @PostMapping("/search")
    public Result search(@RequestBody QueryModel model) {
        return this.singleQuery(model, GiftRecord.class);
    }

    @GetMapping("/getTask/{id}")
    public Result getTask(@PathVariable Long id) {
        GiftRecord giftRecord = giftRecordRepository.findOne(id);
        AccountChangeDetails changeDetails = accountChangeDetailsRepository.findByRecordIdAndRecordType(id, StateConstants.RECORD_TYPE_GIFT);
        JSONObject json = new JSONObject();
        json.put("medicalNumber", giftRecord.getMemberNumber());
        json.put("memberName", giftRecord.getMemberName());
        json.put("afterLevelName", changeDetails.getAfterLevelName() == null ? "普通会员" : changeDetails.getAfterLevelName());
        json.put("afterGiftAccount", changeDetails.getAfterGiftAccount());
        json.put("giftAmount", giftRecord.getGiftAmount());
        json.put("remark", giftRecord.getGiftRemark());
        json.put("creationTime", DateFormatUtils.format(giftRecord.getCreationTime(), "yyyy-MM-dd HH:mm:ss"));
        json.put("createdBy", giftRecord.getCreatedBy());
        return ResultUtil.success(json);
    }
}
